/*
 * Copyright 2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.seppiko.pigeon.utils;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.lang.reflect.InvocationTargetException;
import lombok.extern.slf4j.Slf4j;

/**
 * Jackson Util
 *
 * @author Leonard Woo
 */
@Slf4j
public class JsonUtil {

  private static final ObjectMapper mapper = new ObjectMapper();

  static {
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.setSerializationInclusion(Include.NON_EMPTY);
    mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
    mapper.enable(DeserializationFeature.USE_LONG_FOR_INTS);
  }

  public static <T> String toJson(T t) {
    try {
      return mapper.writeValueAsString(t);
    } catch (JsonProcessingException e) {
      log.warn("Json generator failed.", e);
    }
    return "{}";
  }

  public static <T> T fromJson(String json, Class<T> type) {
    try {
      T t = mapper.readValue(json, type);
      return t.equals(type.getDeclaredConstructor().newInstance()) ? null : t;
    } catch (JsonProcessingException | NoSuchMethodException | InstantiationException |
        IllegalAccessException | InvocationTargetException e) {
      log.warn("Json parse failed.", e);
      return null;
    }
  }

  public static <T> ObjectNode toJsonObject(T t) {
    try {
      return mapper.convertValue(t, ObjectNode.class);
    } catch (IllegalArgumentException ex) {
      log.error("", ex);
      return null;
    }
  }

  public static JsonNode fromJsonNode(String json) {
    try {
      return mapper.readTree(json);
    } catch (JsonProcessingException ex) {
      log.error("", ex);
      return null;
    }
  }

  public static ObjectNode createJsonObject() {
    return mapper.createObjectNode();
  }
}
